#region Using directives

using System;
using SharpWind.Resources;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;

#endregion

namespace SharpWind.Graphics.Text
{
	public class TextManager
	{
		#region TextPerFont

		private class TextPerFont
		{
			public List<TextBlock> TextBlocks = new List<TextBlock>();

			public Font Font = null;
		}

		#endregion

		#region Fields

		private List<TextPerFont> textPerFont = new List<TextPerFont>();

		#endregion

		#region Methods

		public void Add( TextBlock item )
		{
			TextPerFont tpf = FindTextPerFont( item.Font );
			if( tpf != null )
			{
				tpf.TextBlocks.Add( item );
			}
			else
			{
				TextPerFont newTextPerFont = new TextPerFont();
				newTextPerFont.Font = item.Font;
				newTextPerFont.TextBlocks.Add( item );

				this.textPerFont.Add( newTextPerFont );
			}
		}

		internal void Draw()
		{
			SpriteBatch spriteBatch = Engine.Instance.SpriteBatch;
			spriteBatch.Begin();

			foreach( TextPerFont tpf in this.textPerFont )
			{
				foreach( TextBlock tb in tpf.TextBlocks )
				{
					if( tb.Visible && tb.Font.XnaFont != null )
					{
						spriteBatch.DrawString( tb.Font.XnaFont, tb.Text, tb.Position, tb.Color, tb.Rotation, tb.Origin,
												tb.Scale, tb.SpriteEffects, tb.LayerDepth );
					}
				}
			}

			spriteBatch.End();
		}

		private TextPerFont FindTextPerFont( Font font )
		{
			foreach( TextPerFont tpf in this.textPerFont )
			{
				if( tpf.Font == font )
				{
					return tpf;
				}
			}

			return null;
		}

		#endregion
	}
}
